<template>
  <div>
    <!-- 卡片一 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>商品(Sku)介绍</h3>
        </div>
      </template>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="from.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="初始价格" prop="originalPrice">
          <el-input v-model="from.originalPrice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="price">
          <el-input v-model="from.price">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="VIP价格" prop="vipPrice">
          <el-input v-model="from.vipPrice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="剩余库存" prop="Inventory">
          <el-input
            autocomplete="off"
            disabled
            v-model="addfrom.Inventory"
          ></el-input>
        </el-form-item>
        <el-form-item label="运费模版" prop="pass">
          <el-cascader
            placeholder="请选择"
            :options="optionss"
            :props="props2"
            clearable
            v-model="from.freightTemplateId"
          />
        </el-form-item>
        <el-form-item label="是否在售" prop="pass">
          <el-radio v-model="from.status" :label="1" size="large"
            >在售</el-radio
          >
          <el-radio v-model="from.status" :label="0" size="large"
            >下单</el-radio
          >
        </el-form-item>
        <el-form-item label="商品图片" prop="pass">
          <el-upload
            action="http://192.168.1.188:8080/upload/admin/"
            list-type="picture-card"
            :on-success="lsit"
            :on-remove="handleRemove"
            :file-list="fileList"
            :headers="requestimg"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="from.imgList" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="商品单位" prop="unit">
          <el-input
            v-model="from.unit"
            autocomplete="off"
            placeholder="件"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属类目" prop="pass">
          <el-cascader
            v-model="from.categoryId"
            :options="options"
            :props="props1"
            placeholder="请选择类目"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品简介" prop="pass">
          <el-input
            v-model="from.description"
            autocomplete="off"
            placeholder="商品简介"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品简介" prop="pass">
              <Richtext v-model="from.detail"></Richtext>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 卡片二 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>商品参数</h3>
        </div>
      </template>
      <el-button type="primary" plain @click="add()">添加</el-button>
      <el-table :data="from.attributeList" style="width: 100%">
        <el-table-column prop="attribute" label="商品参数名称" />
        <el-table-column prop="value" label="商品参数值" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              @click="deleteone(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加对话框 -->
    <!-- 卡片三 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>规格维度</h3>
        </div>
      </template>
      <el-button type="primary" plain @click="addSpecifications()"
        >添加</el-button
      >
      <el-table :data="from.specificationList" style="width: 100%">
        <el-table-column prop="date" label="维度ID" />
        <el-table-column prop="title" label="维度名称" />
        <el-table-column prop="gmtCreate" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="modifies(scope.row, scope.$index)"
              >修改</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="deletetwo(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 卡片四 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>商品(sku)详情</h3>
        </div>
      </template>
      <el-button type="primary" plain @click="lotsize()">批量定价</el-button>
      <div
        class="tag"
        v-for="(item, index) in from.specificationList"
        :key="index"
      >
        <el-tag type="warning">{{ item.title }}</el-tag>
        <el-tag
          v-for="tag in item.values"
          :key="tag"
          @close="handleClosee(tag, index)"
          closable
          :disable-transitions="false"
        >
          {{ tag }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="item.inputSkuTagVisible"
          ref="InputRef"
          v-model="item.inputSkuTagValue"
          size="small"
          @keyup.enter="handleInputConfirm(item.inputSkuTagValue, index)"
          @blur="handleInputConfirm(item.inputSkuTagValue, index)"
        />
        <el-button
          v-else
          class="button-new-tag ml-1"
          size="small"
          @click="showInput(index)"
          >+添加</el-button
        >
      </div>
      <!-- sku表格 -->
      <el-table
        :data="from.skuList"
        :span-method="objectSpanMethod"
        border
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column
          v-for="item in from.specificationList"
          :prop="'id_' + item.title"
          :label="item.title"
          width="140"
          :key="item.id"
        />
        <el-table-column prop="amount1" label="Skuld" />

        <el-table-column prop="price" label="￥价格(元)" width="180px">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.price"
              :precision="2"
              :step="1"
            />
          </template>
        </el-table-column>
        <el-table-column prop="vipPrice" label="￥VIP价(元)" width="180px">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.vipPrice"
              :precision="2"
              :step="1"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="originalPrice"
          label="￥吊牌价(元)"
          width="180px"
        >
          <template #default="scope">
            <el-input-number
              v-model="scope.row.originalPrice"
              :precision="2"
              :step="1"
            />
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存(件)" width="180px">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.stock"
            />
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="重量(克)" width="180px">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.weight"
            />
          </template>
        </el-table-column>
        <el-table-column prop="img" label="SKU图片">
          <template #default="scope">
            <el-upload class="avatar-uploader" action="http://192.168.1.188:8080/upload/admin/" :show-file-list="false"
            :on-success="handleAvatar"  :headers="requestimg">
              <img :src="scope.row.img" class="avatar" v-if="scope.row.img" />
              <el-icon v-else  class="avatar-uploader-icon" @click="show(scope.$index)">
                <Plus />
              </el-icon>
            </el-upload>
          </template>
          <!-- 1111111111 -->
        </el-table-column>
        <el-table-column prop="barCode" label="条形码" width="180px">
          <template #default="scope">
            <el-input v-model="scope.row.barCode" >
              <template #append>
                <div @click="suiji(scope.$index)">随机</div>
              </template>
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="botton">
        <el-button plain @click="handleClose($route.path)">取消</el-button
        ><el-button type="primary" @click="ess($route.path)">保存商品</el-button>
      </div>
    </el-card>
    <!-- 商品参数对话框 -->
    <el-dialog v-model="adddialogVisible" title="设置商品参数" width="30%">
      <el-form
        ref="addruleForm"
        :model="addruleForm"
        :rules="commodities"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="商品参数名称" prop="attribute">
          <el-input v-model.trim="addruleForm.attribute" />
        </el-form-item>
        <el-form-item label="商品参数值" prop="value">
          <el-input v-model.trim="addruleForm.value" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adddialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addsure('addruleForm')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 规格添加对话框 -->
    <el-dialog v-model="cationdialogue" title="添加" width="30%">
      <el-form
        ref="Specifi"
        :model="Specifi"
        :rules="Specificationdialogue"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model.trim="Specifi.title" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cationdialogue = false">取消</el-button>
          <el-button type="primary" @click="Specificationsure('Specifi')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 规格修改对话框 -->
    <el-dialog v-model="cationdialogues" title="修改" width="30%">
      <el-form
        ref="Specifi"
        :model="Specifi"
        :rules="Specificationdialogue"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model.trim="Specifis.title" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cationdialogues = false">取消</el-button>
          <el-button type="primary" @click="Specificationsures('Specifi')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 批量定价对话框 -->
    <el-dialog v-model="lotsizedialog" title="批量定价" width="30%">
      <el-form
        ref="ruleFormRef"
        :model="lotsizedialog"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="现价(￥)" prop="name">
          <el-input-number
            v-model="lotPricing.price" 
            :precision="2"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="VIP价格(￥)" prop="name">
          <el-input-number
            v-model="lotPricing.vipPrice" 
            :precision="2"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="吊牌价格(￥)" prop="name">
          <el-input-number
            v-model="lotPricing.originalPrice" 
            :precision="2"
            :step="1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="lotsizedialog = false">取消</el-button>
          <el-button type="primary" @click="lotsizesure()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  import cookie from "js-cookie";
  import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
  import { ElMessage } from "element-plus";
  import http from "@/http";
  import Richtext from "@/components/Richtext/Richtext";
  import {mapMutations,mapActions} from "vuex"

  import axios from "axios";
  export default {
    components: {
      Richtext,
    },
    data() {
      return {
        imger:null,
        ruleForm: [],
        from: {
          title: "", //标题
          price: 0, //当前价格
          originalPrice: 0, //原价
          vipPrice: 0, //vip价格
          freightTemplateId: "", //运费模版
          status: 1, //在售或者不售
          imgList: [], //商品图片数组
          unit: '', //件
          categoryId: "", //所属类目ID
          description: "", //简介
          detail: "", //详细信息
          img: "", //默认图片第一张
          attributeList: [], //商品参数表格
          specificationList: [], //规格维度表格
          skuList: [], //sku表格数组
        },
        //商品参数
        addruleForm: {
          attribute: "",
          value: "",
        },
        //接受的规格参数表格

        //规格参数
        Specifis: {
          title: "",
        },
        Specifi: {
          title: "",
          values: [],
          inputSkuTagVisible: false,
          gmtCreate: null,
          gmtUpdate: null,
          inputSkuTagValue: "",
        },
        //批量定价
        lotPricing: {
          originalPrice: 0, //原价格
          price: 0, //现价
          vipPrice: 0, //vip价格
        },

        stock: "",
        weight: "", //重量
        barCode: "", //条形码
        stock: "", //库存
        num: 0,
        adddialogVisible: false, //商品参数对话框
        cationdialogue: false, //规格维度对话框
        cationdialogues: false, //规格维度修改
        lotsizedialog: false, //批量定价对话框
        tableData: [],
        options: [], //类目树
        optionss: [], //运费模版
        props1: {
          children: "childrenList",
          label: "title",
          value: "id",
          checkStrictly: true,
          emitPath: false,
        },
        props2: {
          children: "childrenList",
          label: "title",
          value: "id",
          checkStrictly: true,
          emitPath: false,
        },
        addfrom: {
          title: "", //名称
          priceRaw: 0, //初始价格
          originalPriceRaw: 0, //当前价格
          vipPriceRaw: 1, //vip价格
          Inventory: 0, //库存
        },
        tableDataobj: [],

        //商品参数校验
        commodities: {
          attribute: [
            { required: true, message: "请输入参数名称！", trigger: "blur" },
          ],
          value: [
            { required: true, message: "请输入参数值！", trigger: "blur" },
          ],
        },
        //规格维度校验
        Specificationdialogue: {
          title: [
            { required: true, message: "类型名称不能为空！", trigger: "blur" },
          ],
        },
      };
    },

    created() {
      this.category();
      this.freight();
      this.requestimg = {
        AdminToken: cookie.get("token"),
      };
    },
    methods: {
      ...mapActions(['handleClose']),
      //上传时候的钩子
      lsit(res) {
        // console.log(res);
        // let url = res.url
        this.from.imgList.push(res.url) 
        // if (res.response.errno == 200) {
        //   this.from.imgList = res.response.url;
        // }
      },
      //随机数获取时间戳
      suiji(index){
        let time = +new Date 
        console.log(time);
        this.from.skuList[index].barCode = time
      },
      //定义一个下标
      show(index) {
        this.imger = index
      },
      //上传图片成功的回调
      handleAvatar(res) {
        console.log(res);
        this.from.skuList[this.imger].img = res.url
      },

      //类目树
      category() {
        let leimu = {
          _gp: "admin.category",
          _mt: "categoryTree",
        };
        http.post(leimu).then((res) => {
          console.log(res);
          this.options = res.data;
        });
      },
      //运费模版
      freight() {
        let freights = {
          _gp: "admin.freight",
          _mt: "list",
        };
        http.post(freights).then((res) => {
          console.log(res);
          this.optionss = res.data;
        });
      },
      //商品参数添加
      add() {
        this.adddialogVisible = true;
      },

      //添加确定按钮
      addsure(addruleForm) {
        this.$refs[addruleForm].validate((valid) => {
          if (valid) {
            this.from.attributeList.push(this.addruleForm);
            ElMessage.success("添加成功!");
            this.adddialogVisible = false;
            this.addruleForm = this.$options.data().addruleForm;
          } else {
            // ElMessage.error("参数校验失败！");
            return false;
          }
        });
      },
      //商品添加删除
      deleteone(row, index) {
        // console.log(row,index);
        this.from.attributeList.splice(index, 1);
      },
      //规格删除
      deletetwo(row, index) {
        this.from.specificationList.splice(index, 1);
      },
      // 规格维度添加
      addSpecifications() {
        this.cationdialogue = true;
        this.Specifi = this.$options.data().Specifi;
      },
      //规格维度修改
      modifies(row, index) {
        // console.log(row, index);
        this.cationdialogues = true;
        Object.assign(this.Specifis, {
          title: row.title,
          gmtCreate: row.gmtCreate,
          gmtUpdate: row.gmtUpdate,
          index,
        });
      },
      //修改
      Specificationsures() {
        this.from.specificationList[this.Specifis.index].title =
          this.Specifis.title;
        // console.log(this.specificationList.title );
        this.cationdialogues = false;
      },
      //添加规格确定
      Specificationsure(row) {
        this.$refs[row].validate((valid) => {
          if (valid) {
            if ((this.title = "创建规格")) {
              this.from.specificationList.push({
                title: this.Specifi.title,
                gmtCreate: +new Date(),
                gmtUpdate: +new Date(),
                values: [],
                inputSkuTagVisible: false,
                inputSkuTagValue: "",
              });
              // this.specificationList = +new Date(gmtCreate)
              this.cationdialogue = false;
            }
          } else {
            return false;
          }
        });
      },
      //批量定价点击
      lotsize() {
        this.lotsizedialog = true
      },
      //批量定价
      lotsizesure() {
          let dinner = this.lotPricing
          this.from.skuList.forEach(item=>{
            item.price = dinner.price
            item.originalPrice = dinner.originalPrice
            item.vipPrice = dinner.vipPrice
          })
          this.lotsizedialog = false
         
      },
      //删除tag标签
      handleClosee(tag, index) {
        // console.log(index);
        let arrdelete = this.from.specificationList[index].values;
        arrdelete.splice(arrdelete.indexOf(tag), 1);
      },
      //添加按钮
      showInput(index) {
        // console.log(index)
        this.from.specificationList[index].inputSkuTagVisible = true; //输入框显示
      },
      //追加标签
      handleInputConfirm(inputValue, index) {
        // console.log(inputValue);
        let arr = this.from.specificationList;
        //添加tag
        if (inputValue) {
          arr[index].values.push(inputValue);
        }
        arr[index].inputSkuTagVisible = false;
        arr[index].inputSkuTagValue = "";

        let arra = [];
        arr.forEach((item) => {
          arra.push(item.values);
        });
        //卡迪尔积分算法
        let list = arra.reduce(
          (total, list) => {
            let arrlist = [];
            total.forEach((item) => {
              list.forEach((val) => {
                arrlist.push(item.concat(val));
              });
            });
            return arrlist;
          },
          [[]]
        );

        if (arr.length > 1) {
          this.from.skuList = [];
          list.forEach((item) => {
            let obj = {
              price: this.lotPricing.price,
              vipPrice: this.lotPricing.vipPrice,
              originalPrice: this.lotPricing.originalPrice,
              stock: 0,
              weight: 0,
              img: "",
            };
            arr.forEach((val, index) => {
              obj["id_" + val.title] = item[index];
            });
            this.from.skuList.push(obj);
          });
        } else {
          let obj = {
            price: "",
            price: 0,
            vipPrice: 0,
            originalPrice: 0,
            stock: 0,
            weight: 0,
            img: "",
          };
          arr[0].values.forEach((item) => {
            obj["id_" + arr[0].title] = item;
          });
          this.from.skuList.push(obj);
        }
        //表格数据处理
        this.from.skuList.forEach(item=>{
            let odd = []
            let odds = []
            for (const key in item) {
              if(0<=key.indexOf('id_')){
                odd.push(item[key])
                odds.push(key.slice(3)+'_'+item[key])
              }
            }
            item['title'] = odd.join()
            item['specification'] = odds.join()
            // console.log(item['title']);
        })
      },
      //确定按钮
      ess(index) {
        this.from.img = this.from.imgList[0]
        let data = {
          _gp: "admin.product",
          _mt: "create",
          spuDTO:JSON.stringify(this.from)
        }
        http.post(data).then((res)=>{
          console.log(res);
          if(200==res.errno){
            ElMessage.success("创建成功！")
            this.handleClose(index)
          }else{
            ElMessage.error(res.errmsg)
          }
            
        })
      },
    },
  };
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 40px;
  height: 40px;
  display: block;
}
</style>
<style lang="less" scoped>
  h3 {
    padding: 0px;
    margin: 0px;
    margin-left: 18px;
  }
  .botton {
    margin-top: 20px;
  }
  .el-card /deep/ .el-card__header {
    border: none;
    padding: 0px;
    margin-top: 15px;
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 40px;
    height: 40px;
    border: 1px solid #ccc;

  }

  .tag {
    margin-top: 20px;
    .el-tag {
      margin-right: 8px;
    }
    .mx-1 {
      margin-right: 5px;
    }
    .input-new-tag {
      width: 90px;
      vertical-align: bottom;
    }
  }
</style>
